package hms.UserAccountsModule;

import hms.generic.GUIViewBuilder;
import hms.properties.Properties;

import java.util.Arrays;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class AddUserController {
	
	private JTextField usernameField;
	private JPasswordField passwordField;
	private JLabel usernameLabel;
	private JLabel passwordLabel;
	private JLabel title;
	
	// Main GUIViewBuilder for program
	GUIViewBuilder builder;
	
	// UserAccountcontrol of parent window
	UserAccountControl uac;
	
	public AddUserController(GUIViewBuilder mainBuilder, UserAccountControl uac){
		
		// Assign GUI to local variable
		builder = mainBuilder;
		
		// Create the login JOptionPane if logging-in
		addNewUserDialog();
		
	}
	
	private void addNewUserDialog(){
		
		usernameField = new JTextField();
		passwordField = new JPasswordField();
		
		title = new JLabel("Enter new user's credentials");
		usernameLabel = new JLabel("Username:");
		passwordLabel = new JLabel("Password:");

		Object[] componentsArray = { 
				title,
				usernameLabel, 
                usernameField,
                passwordLabel,
                passwordField};
		
		Object[] options = {"Login", "Cancel"};
		
		int response = JOptionPane.showOptionDialog(null, 
				componentsArray, 
				"Add new user",
				JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE,
                null,
                options,
                componentsArray[1]);
		
		if(response == JOptionPane.YES_OPTION){	
			validateUserCredentials();
		}
	}
	
	
	private void validateUserCredentials(){
		
		boolean errorMsg = false;
		
		// Feedback message
		String feedbackMsg = null;
		
		// Store the values from the input fields locally
		String i_username = usernameField.getText();
		String i_password = passwordField.getPassword().toString();
		
		if(uac.getByUsername(i_username)==null){
			if(i_password.length()>=8) {
				uac.add(new UserAccount(i_username,i_password));
				feedbackMsg = new String(i_username+" has been successfully added.");
			} else {
				feedbackMsg = new String("Password mus be at least 8 characters in length.");
				errorMsg = true;
			}
		} else {
			feedbackMsg = new String("Username must be unique!");
			errorMsg = true;
		}
		
		
		JOptionPane.showMessageDialog(null, feedbackMsg, (errorMsg)?"Invalid Input":"Success!", JOptionPane.INFORMATION_MESSAGE);
		
	}

}
